<template>
    <div class v-if="showEdit" :style="width">
        <div class="sava-box" v-if="show_save">
            <div class="item tips">
                <span>实时保存仅限输入 其他操作组件不保证实时保存 请自行点击保存</span>
            </div>
            <div class="item">
                <span>开启实时保存</span>：
                <el-switch v-model="is_save_now"></el-switch>
            </div>
        </div>
        <Editor v-model="editValue" :init="editConfig" />
    </div>
</template>
<script setup lang="ts">
import { ref, watch, nextTick, onMounted, computed } from "vue";
import "/public/tinymce/tinymce.min";
import Editor from "@tinymce/tinymce-vue";
import "/public/tinymce/tinymce.d";
import { uploadEditorImg } from "@/api/api";

const emit = defineEmits(["update:value", "save"]);
const props = defineProps({
    height: {
        type: [Number, String],
        default: () => {
            return 500;
        },
    },
    value: {
        type: String,
        default: () => {
            return "";
        },
    },
    width: {
        type: String,
        default: () => {
            return "100%";
        },
    },
    show_save: {
        type: Boolean,
        default: () => {
            return true;
        },
    },
    placeholder: {
        type: String,
        default: () => {
            return "请输入内容";
        },
    },
    // hash模式下打包的路径
    production_url: {
        type: String,
        default: () => {
            return ""
        }
    },
    // 菜单配置
    plugins: {
        type: Array,
        default: () => {
            return [
                'anchor', 'autolink', 'charmap', 'codesample', 'emoticons', 'image', 'link', 'lists', 'media', 'searchreplace', 'table', 'visualblocks', 'wordcount',
                'checklist', 'mediaembed', 'casechange', 'export', 'formatpainter', 'pageembed', 'a11ychecker', 'tinymcespellchecker', 'permanentpen', 'powerpaste', 'advtable', 'advcode', 'editimage', 'advtemplate', 'mentions', 'tinycomments', 'tableofcontents', 'footnotes', 'mergetags', 'autocorrect', 'typography', 'inlinecss', 'markdown', 'help', 'save',
            ]
        }
    },
    // 快捷键配置
    toolbar: {
        type: String,
        default: () => {
            return 'undo redo save | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | addcomment showcomments | spellcheckdialog a11ycheck typography | align lineheight | checklist numlist bullist indent outdent | emoticons charmap | removeformat'
        }
    }
})

const editConfig = ref({});
const editValue = ref("");
const is_save_now = ref(true); //是否实时保存
const showEdit = ref(false);

const initEditor = () => {
    editConfig.value = {
        base_url: '/tinymce',
        suffix: ".min",
        toolbar_mode: 'sliding',
        skin_url: '/tinymce/skins/ui/tinymce-5',
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        plugins: props.plugins,
        toolbar: props.toolbar,
        branding: true, // 去水印
        height: props.height || 500, //编辑器高度
        tinycomments_mode: 'embedded',
        tinycomments_author: 'Author name',
        file_picker_types: "image",
        images_upload_credentials: true,
        placeholder: props.placeholder,
        autosave_interval: "20s",
        font_family_formats:
            "微软雅黑=Microsoft YaHei,Helvetica Neue;PingFang SC;sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun;serifsans-serif;Terminal=terminal;monaco;Times New Roman=times new roman;times", //字体
        mergetags_list: [
            { value: 'First.Name', title: 'First Name' },
            { value: 'Email', title: 'Email' },
        ],
        images_upload_handler: function (blobInfo: any, success: Function, failure: Function) {
            return new Promise((resolve, reject) => {
                let formData = new FormData();
                formData.append("file", blobInfo.blob());
                uploadEditorImg(formData).then((res: any) => {
                    if (res.code == 200) {
                        resolve(res.data.path + res.data.url)
                    } else {
                        reject(res.message)
                    }
                })
            });
        },
        save_onsavecallback: function () {
            save();
        },
        init_instance_callback: (editor: any) => {
            editor.on("change", () => {
                if (is_save_now.value) {
                    save();
                }
            })
        }
    }
    showEdit.value = false;
    editValue.value = props.value ? props.value : "";
    setTimeout(() => {
        showEdit.value = true;

    }, 50);
}

onMounted(() => {
    initEditor();
})

const save = () => {
    editValue.value = editValue.value.replace(/'/g, "&#39;");
    emit("update:value", editValue.value);
    emit("save", editValue.value);
}

watch(() => props.value, (newValue) => {
    editValue.value = newValue ? newValue : "";
}, {
    immediate: true,
    deep: true,
})

watch(() => props.toolbar, (newValue) => {
    nextTick(() => {
        initEditor();
    })
}, {
    immediate: true,
    deep: true,
})

</script>
<style lang="scss" scoped></style>